	<template>
		<view class="page">
			<view class="custom-navbar" :style="{ paddingTop: statusBarHeight + 'px' }">
				<view class="nav-content">
					<view class="nav-left" @click="blackWork">
						<image class="back-icon" src="@/static/images/back.png" mode="widthFix" />
					</view>
					<view class="nav-title">{{ title }}</view>
					<view class="nav-right"></view>
				</view>
			</view>
			<view class="content">

				<view class="search-box">
					<view class="form-row">
						<input class="search-input" placeholder="客户名称" v-model="search.fCustId_FName" />
						<input class="search-input" placeholder="订单编号" v-model="search.fBillNo" />
						<uni-datetime-picker v-model="search.dateRange" type="daterange" rangeSeparator="至"
							placeholder="选择日期范围" class="search-input" />
					</view>

					<view class="form-actions">
						<button class="btn-search" @click="getSaleOrderList">搜索</button>
						<button class="btn-reset" @click="resetSearch">重置</button>
					</view>
				</view>
				<block v-for="(order, index) in orders" :key="index">
					<uni-card class="order-item" isShadow>
						<!-- 订单头部 -->
						<view class="order-header">
							<text class="order-customer">单据日期： {{formatDate( order.fDate) }}</text>
							<text class="order-customer">客户名称：{{ order.fCustId_FName }}</text>
							<text class="order-customer">订单号：{{ order.fBillNo }}</text>
							<text class="order-customer">销售员：{{ loginName }}</text>

							<text
								class="order-customer">订单状态：{{ order.fDocumentStatus === 'A' ? '创建' : order.fDocumentStatus === 'B' ? '审核中' : order.fDocumentStatus === 'C' ? '已审核' : '未知' }}</text>

              <text class="order-customer">总金额：💰 {{ formatAmount(calculateOrderTotal(order)) }} ￥</text>

            </view>



						<!-- 明细部分 -->
						<view class="order-entries">
							<view v-for="(entry, idx) in order.fEntry" :key="idx" class="entry-item">
								<view class="entry-header">
									<text class="entry-name">{{ entry.fMaterialId_FName }}</text>
									<text class="entry-code">#{{ entry.fMaterialId_FNumber }}</text>
								</view>
								<view class="entry-info">
									<text>数量：{{formatNumber(entry.fQty)}} 箱</text>
									<text>已发：{{formatNumber(entry.fStockOutQty)}} 箱</text>
									<text>未发：{{formatNumber(entry.fRemainOutQty)}} 箱</text>
								</view>
								<view class="entry-amount">
									💰 {{ formatAmount(entry.fAmount)  }} ￥
								</view>
							</view>
						</view>
						<view class="order-actions">
							<button size="mini" v-if="order.fDocumentStatus === 'A'" type="primary"
								@click="editOrder(order)">修改</button>
						</view>
					</uni-card>
				</block>
				<view class="floating-btn" @click="goAddOrder">
					➕
				</view>
			</view>
		</view>

	</template>

	<script>
		import {
			salesList
		} from '@/api/saleOrder.js'

		export default {


			data() {
				return {
					statusBarHeight: 0,
					title: '销售订单',
					loginName: this.$store.state.user.name,
					keyword: '', // 搜索关键词
					orders: [],
					search: {
						//订单编号
						fCustId_FNumber: "",
						//销售人员名称
						fSalerId_FName: this.$store.state.user.name,
						// 客户名称
						fCustId_FName: "",
						dateRange: []
					}
				}
			},
			created() {
				this.setDefaultDateRange(7)


			},

			onLoad() {
				// 获取状态栏高度，适配刘海屏/不同手机
				const sys = uni.getSystemInfoSync()
				this.statusBarHeight = sys.statusBarHeight || 20
				this.getSaleOrderList();
			},
			onBackPress() {
				debugger
				uni.redirectTo({
					url: '/pages/work/index'
				});
				return true; // 阻止默认返回
			},
			methods: {
				blackWork() {
					uni.switchTab({
						url: '/pages/work/index'
					})
				},
				editOrder(order) {

					if (order.fDocumentStatus != "A") {
						uni.showToast({
							title: "只有创建状态可以修改！！",
							icon: 'warn'
						})
					}
					uni.removeStorageSync("saveNote")
					uni.removeStorageSync("goodsList")
					uni.removeStorageSync("editOrderData")
					uni.setStorageSync("editOrderData", order); // 临时存储订单数据
					uni.navigateTo({
						url: '/pages/placeAnOrder/moveTheOrder?mode=edit' // 带上 mode=edit 参数
					});
				},
				goAddOrder() {
					uni.removeStorageSync("saveNote")
					uni.removeStorageSync("goodsList")
					uni.removeStorageSync("formData")
					uni.redirectTo({
						url: '/pages/placeAnOrder/moveTheOrder?mode=add' // 这里换成你实际的下单页面路径
					})
				},
				setDefaultDateRange(days = 7) {
					const today = new Date()
					const startDate = new Date()
					startDate.setTime(today.getTime() - (days - 1) * 24 * 60 * 60 * 1000) // 减去 N-1 天

					// 格式化为 'YYYY-MM-DD' 字符串
					const formatDate = (date) => {
						const y = date.getFullYear()
						const m = String(date.getMonth() + 1).padStart(2, '0')
						const d = String(date.getDate()).padStart(2, '0')
						return `${y}-${m}-${d}`
					}
					this.search.dateRange = [
						formatDate(startDate), // 开始时间
						formatDate(today) // 结束时间
					]
					console.log(JSON.stringify(this.dateRange))
				},
				resetSearch() {
					this.search.dateRange = [];
					this.search.fCustId_FNumber = "";
					this.search.fCustId_FName = ""
				},
				formatNumber(val, decimals = 2) {
					if (!val) return '0.00'
					return Number(val).toFixed(decimals)
				},
				formatAmount(val) {
					if (!val) return '0.00'
					return Number(val).toLocaleString('zh-CN', {
						minimumFractionDigits: 2
					})
				},
				formatDate(dateStr) {
					if (!dateStr) return ''
					// 替换 T 为 " "，避免 iOS 解析失败
					const date = new Date(dateStr.replace(/T/g, ' '))
					const y = date.getFullYear()
					const m = String(date.getMonth() + 1).padStart(2, '0')
					const d = String(date.getDate()).padStart(2, '0')
					return `${y}-${m}-${d}`
				},
				getSaleOrderList() {

					let queryParams = this.search;

					queryParams.params = {};
					if (queryParams.dateRange.length > 0) {
						queryParams.params["startTime"] = queryParams.dateRange[0];
						queryParams.params["endTime"] = queryParams.dateRange[1];
					}
					salesList(
						queryParams
					).then(res => {
						// 假设后端返回的数据格式是 { code: 200, data: [...] }
						if (res.code === 200) {
							this.orders = res.data
						}
					}).catch(err => {
						console.error('获取订单失败:', err)
					})
				},
        // 添加计算订单总金额的方法
        calculateOrderTotal(order) {
          if (!order.fEntry || !Array.isArray(order.fEntry)) {
            return 0;
          }

          return order.fEntry.reduce((total, entry) => {
            return total + (parseFloat(entry.fAmount) || 0);
          }, 0);
        },

			}
		}
	</script>
	<style scoped>
		.page {
			background-color: #f5f5f5;
			min-height: 100vh;
		}

		.custom-navbar {
			width: 100%;
			background-color: #ffffff;
			box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
			z-index: 1000;
		}

		.nav-content {
			display: flex;
			align-items: center;
			justify-content: space-between;
			height: 44px;
			padding: 0 10px;
		}

		/* 左侧返回按钮区域 */
		.nav-left {
			width: 60rpx;
			display: flex;
			align-items: center;
			justify-content: flex-start;
		}

		.back-icon {
			width: 22px;
			height: 22px;
		}

		/* 中间标题 */
		.nav-title {
			flex: 1;
			text-align: center;
			font-size: 26rpx;
			font-weight: 500;
			color: #000;
		}

		/* 右侧预留空间（对称用） */
		.nav-right {
			width: 60rpx;
		}

		/* 左侧返回区 */
		.left-area {
			position: absolute;
			left: 10px;
			display: flex;
			align-items: center;
		}

		/* 返回箭头图标 */
		.back-icon {
			width: 22px;
			height: 22px;
		}

		/* “返回”文字 */
		.back-text {
			font-size: 16px;
			color: #333;
			margin-left: 2px;
		}

		/* 标题居中 */
		.title {
			font-size: 18px;
			font-weight: bold;
			color: #000;
		}

		/* 内容 */
		.content {
			padding-top: 60px;
		}

		.content {
			padding: 20px;
		}

		.order-item text {
			display: flex;
			flex-direction: column;
			/* 子元素从上到下排列 */

		}

		.floating-btn {
			position: fixed;
			right: 40rpx;
			bottom: 120rpx;
			/* 避开底部 tabbar/按钮 */
			width: 100rpx;
			height: 100rpx;
			border-radius: 50%;
			background: #4caf50;
			color: #fff;
			font-size: 48rpx;
			text-align: center;
			line-height: 100rpx;
			box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.2);
			z-index: 999;
		}

		.order-item {
			margin-bottom: 20px;
			border-bottom: 1px solid #ccc;
			padding-bottom: 10px;
		}

		.order-item {
			margin-bottom: 20px;
			border-radius: 12px;
			overflow: hidden;
		}

		.order-header {
			background: #f6f9fc;
			padding: 8px 12px;
			border-radius: 8px;
			margin-bottom: 10px;
		}

		.order-date {
			font-size: 14px;
			font-weight: bold;
			color: #333;
			margin-right: 10px;
		}

		.order-customer {
			font-size: 14px;
			color: #666;
		}



		.order-entries {
			border-top: 1px dashed #ddd;
			padding-top: 10px;
		}

		.entry-item {
			background: #fff;
			border: 1px solid #f0f0f0;
			border-radius: 8px;
			padding: 10px;
			margin-bottom: 10px;
		}

		.entry-header {
			display: flex;
			justify-content: space-between;
			margin-bottom: 6px;
		}

		.entry-name {
			font-size: 14px;
			font-weight: bold;
			color: #333;
		}

		.entry-code {
			font-size: 12px;
			color: #999;
		}

		.entry-info {
			font-size: 13px;
			color: #555;
			line-height: 1.6;
			display: flex;
			justify-content: space-between;
		}

		.entry-amount {
			margin-top: 6px;
			font-size: 14px;
			font-weight: bold;
			color: #e67e22;
			text-align: right;
		}

		.search-box {
			background: #fff;
			border-radius: 12px;
			padding: 16px;
			box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
			margin: 10px;
		}

		.form-row {
			display: flex;
			flex-wrap: wrap;
			gap: 12px;
			flex-direction: column;
		}

		.search-input {
			flex: 1;
			min-width: 180px;
			height: 40px;
			border: 1px solid #ddd;
			border-radius: 8px;
			padding: 0 10px;
			font-size: 14px;
			background-color: #fafafa;
		}

		.form-actions {
			display: flex;
			gap: 12px;
			margin-top: 12px;
		}

		.btn-search {
			flex: 1;
			height: 40px;
			background: #4caf50;
			color: #fff;
			border-radius: 8px;
			border: none;
			font-size: 15px;
		}

		.btn-reset {
			flex: 1;
			height: 40px;
			background: #f5f5f5;
			color: #333;
			border-radius: 8px;
			border: 1px solid #ddd;
			font-size: 15px;
		}
	</style>